﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class OpMenu : MonoBehaviour {

    public GameObject Op;

    List<GameObject> btns = new List<GameObject>();
	public void Refresh(string[][] ops, Action<string> onOp)
    {
        ClearAll();

        foreach (var g in ops)
        {
            foreach (var op in g)
            {
                var opName = op;
                var btn = Instantiate(Op);
                btn.transform.SetParent(transform, false);
                btn.SetActive(true);
                btns.Add(btn);

                if (opName != null)
                {
                    btn.GetComponentInChildren<Text>().text = opName;
                    btn.GetComponent<Button>().onClick.AddListener(new UnityAction(() => onOp(opName)));
                }
                else
                {
                    // 占个位置好排版
                    btn.GetComponentInChildren<Text>().color = new Color(0, 0, 0, 0);
                    btn.GetComponent<Image>().color = new Color(0, 0, 0, 0);
                    btn.GetComponent<Button>().onClick.AddListener(new UnityAction(() => gameObject.SetActive(false)));
                }
            }
        }

        var glg = GetComponent<GridLayoutGroup>();
        glg.constraint = GridLayoutGroup.Constraint.FixedRowCount;
        glg.constraintCount = ops.Length;
    }

    void ClearAll()
    {
        foreach (var go in btns)
            Destroy(go);

        btns.Clear();
    }
}
